<!--
 * @Author: yl
 * @Date: 2024-04-09 16:07:23
 * @LastEditTime: 2024-04-09 16:07:23
 * @LastEditors: Please set LastEditors
 * @Description: 系统个体溯源页面
-->
<template>
  <BaseMainSlot :show-tab="false" :show-search-box="false">
    <template v-slot:btn-box>
      <ActionBar
        v-show="!showTraceInfo"
        :page-no="602"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @edit="edit"
        @del="del"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label"></div>
          <div class="input"></div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <ZnFilterTable
        v-if="tableUpStauts === 1 && !showTraceInfo"
        :loadings="loading"
        :list-data="tableData"
        :prop-list="tableDataList"
        scope-no="traceConfigNo"
        @handleSelectionChange="handleSelectionChange($event, 'traceConfigNo')"
        @tableUpdate="tableUpdate"
      >
        <template v-slot:url="{ row }">
          <el-button
            class="text-btn-cursor"
            type="text"
            size="small"
            @click="previewImg(row)"
          >点击查看</el-button>
        </template>
        <template v-slot:operation="{ row }">
          <el-button
            class="text-btn-cursor"
            type="text"
            size="small"
            @click="handleTraceInfor(row)"
          >
            <i class="el-icon-edit-outline"></i> 查看溯源信息
          </el-button>
          <el-button
            v-if="judgePermission(602, 'edit')"
            class="text-btn-cursor"
            type="text"
            size="small"
            @click="edit(row)"
          >
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>
          <el-button
            v-else-if="!judgePermission(602, 'edit')"
            class="text-btn-cursor"
            type="text"
            size="small"
            disabled
          >
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>

          <el-button
            v-if="judgePermission(602, 'delete')"
            class="text-btn-cursor cursor-delete"
            type="text"
            size="small"
            @click="handleDelete(row.traceConfigNo)"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <el-button
            v-else-if="!judgePermission(602, 'delete')"
            class="text-btn-cursor cursor-delete"
            type="text"
            size="small"
            disabled
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </znfiltertable>
      <Pagination
        v-show="!showTraceInfo"
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />

      <TraceInformation v-if="showTraceInfo" ref="traceInfo" @back="TraceInforClose" />
    </template>
    <template v-slot:dialog>
      <SheepSelect
        v-if="sheepSelectDialog"
        need-flag
        :select-type="selectType"
        :initial-parameters="initialParameters"
        @closeSheepSelect="closeSheepSelect"
        @selectedSheep="selectedSheep"
      />
      <el-dialog
        :title="titleText + '溯源信息'"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDataList"
            :key="index"
            :label="item.name + ':'"
            :prop="item.porp"
            class="w100p"
          >
            <el-input
              v-if="item.type === 'input'&&item.inputType !== 'number'"
              v-model="formData[ `${item.porp}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-input-number
              v-if="item.type === 'input'&&item.inputType === 'number'"
              v-model.number="formData[ `${item.porp}`]"
              :type="item.inputType"
              :placeholder="'请输入' + item.name"
              clearable
              controls-position="right"
              :min="0"
            />
            <el-select
              v-if="item.type === 'Select' && item.linkage === 'sheepNo'"
              :ref="item.linkage"
              v-model="formData[ `${item.porp}`]"
              :placeholder="livestock('请选择耳标')"
              clearable
              :multiple="item.multiple"
              :disabled="nowChanceStau === 'edit'"
              collapse-tags
              :value-key="item.linkage"
              @focus="openSheep(item.linkage)"
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items[item.typeObj.listName[0]]"
                :value="items[item.typeObj.listName[1]]"
              />
            </el-select>
            <el-select
              v-if="item.type === 'Select' && item.linkage !== 'sheepNo'"
              v-model="formData[ `${item.porp}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
              @change="SelectLinkage($event, item.linkage, item.typeObj.list, index - 1)"
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items[item.typeObj.listName[0]]"
                :value="items[item.typeObj.listName[1]]"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.porp}`]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="'选择' + item.name"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixins";
import SheepSelect from "@/components/sheepSelect";
import TraceInformation from "@/views/trace-source-web/components/traceability-information/index.vue";

import traceConfigApi from "@/api/trace-source-web/traceConfig";
// 生产单位信息
import manufacturerApi from "@/api/trace-source-web/base-infor-manage/manufacturer-management";
// 产品信息
import productApi from "@/api/trace-source-web/base-infor-manage/product-infor-management";
// import productApi from "@/api/trace-source-web/base-infor-manage/product-infor-management";
// 主体信息
import proprietorrApi from "@/api/trace-source-web/base-infor-manage/proprietorr-management";

export default {
  name: "IndividualTraceabilityInformationManage",
  components: {
    ActionBar,
    SearchBox,
    TraceInformation,
    SheepSelect
  },
  mixins: [mymixin],
  data() {
    return {
      showTraceInfo: false,
      sheepSelectDialog: false,
      selectType: "single",
      initialParameters: {},
      breedTypeName: "",
      // 员工姓名
      breedTypeNo: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      delList: [],
      formData: {
        person: {}
      },
      tableDataList: [
        {
          type: "input", // input Select Checkbox TimePicker
          porps: 'individuationInfo',
          porp: "earLabel",
          typeObj: {},
          name: "耳标",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porps: "individuationInfo",
          porp: "eleEarLabel",
          typeObj: {},
          name: "电子耳标",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porps: "individuationInfo",
          porp: "gender",
          typeObj: {},
          name: "性别",
          notSearch: true,
          required: true
          // rules:
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porps: "manufacturer",
          porp: "manufacturerNo",
          porpName: "manufacturerName",
          typeObj: {},
          name: "生产单位",
          notSearch: true,
          required: false
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porps: "proprietor",
          porp: "proprietorNo",
          porpName: "proprietorName",
          typeObj: {},
          notSearch: true,
          name: "主体名称",
          required: false
        },
        {
          type: "date", // input Select Checkbox TimePicker
          porp: "generationDate",
          porpName: "generationDate",
          typeObj: {},
          name: "生成日期",
          required: false
        },
        {
          porp: 'operation', name: '操作', slotName: 'operation', fixed: true,
          minWidth: "160",
          typeObj: {},
          show: false,
          notSearch: true
        }
      ],
      formDataList: [
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "sheepList",
          linkage: 'sheepNo',
          typeObj: {},
          multiple: true,
          name: "羊只耳标",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "proprietorNo",
          linkage: 'proprietor',
          typeObj: {},
          name: "主体名称",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "productNo",
          linkage: 'product',
          typeObj: {},
          name: "关联产品",
          required: true
          // rules:
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "manufacturerNo",
          linkage: 'manufacturer',
          typeObj: {},
          name: "生产单位",
          required: false
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          porp: "factoryDate",
          typeObj: {},
          name: "出厂日期",
          required: false
        }
      ],
      rules: {
        sheepList: [
          {
            required: true,
            message: "耳标不能为空",
            trigger: ["blur", "change"]
          }
        ],
        proprietorNo: [
          {
            required: true,
            message: "主体名称不能为空",
            trigger: ["blur", "change"]
          }
        ],
        productNo: [
          {
            required: true,
            message: "关联产品不能为空",
            trigger: ["blur", "change"]
          }
        ],
        manufacturerNo: [
          {
            required: true,
            message: "生产单位不能为空",
            trigger: ["blur", "change"]
          }
        ],
        factoryDate: [
          {
            required: true,
            message: "出厂日期不能为空",
            trigger: ["blur", "change"]
          }
        ]
      },
      topitemtypestu: true,
      searchObj: {},
      // 图片
      imgObj: {},
      uploadPictureList: [],
      dialogImgVisible: false
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 查询部门
    // 获取表格数据
    this.search();
  },
  methods: {
    handleTraceInfor(row) {
      // console.log(row);
      this.showTraceInfo = true;
      // v-if 得使用 nextTick
      this.$nextTick(() => {
        this.$refs.traceInfo.queryTraceInfo(row, 602);
      })
    },
    TraceInforClose(refresh) {
      if (refresh) {
        this.search();
      }
      this.showTraceInfo = false;
    },
    async getList() {
      // 条件查询生产单位
      manufacturerApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "manufacturerNo",
          list: res.data,
          listName: ["manufacturerName", "manufacturerNo"]
        });
      })
      // 条件查询产品
      productApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "productNo",
          list: res.data,
          listName: ["productName", "productNo"]
        });
      })
      // 条件查询主体
      proprietorrApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "proprietorNo",
          list: res.data,
          listName: ["proprietorName", "proprietorNo"]
        });
      })
    },
    async SelectLinkage(e, linkage, list, x) {
      if (x) {
        let index = list.findIndex(item => item[linkage + 'No'] === e)
        if (index !== -1) {
          this.$set(this.formData, linkage, list[index]);
        }
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchObj,
          "traceType": "个体",
          "sourceType": "系统生成"
        }
      };
      traceConfigApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = JSON.parse(
            this.livestock(JSON.stringify(data.content))
          );
          // console.log(this.tableData)
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list, No) {
      this.delList = [];
      this.delList = list.map((item) => item[No]);
      if (this.delList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      traceConfigApi.numberBatchDel({ noList: this.delList }).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          traceConfigApi.numberDel(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    addPlus() {
      this.uploadPictureList = [];
      this.$set(this.formData, "breedTypeNo", sessionStorage.breedTypeNo);
    },
    editPlus(row) {
      console.log(row);
      this.formData = { ...row }
      this.$set(this.formData, 'sheepList', [row.individuationInfo.sheepNo])
      this.listfor({
        formDataList: "formDataList",
        porp: "sheepList",
        list: [row.individuationInfo],
        listName: ["earLabel", "sheepNo"]
      });
    },
    // 选择养只弹框
    selectedSheep(params) {
      // console.log(params, typeof this.formDataList, this.formDataList)
      // this.formDataList.forEach((item, index) => {
      //   if (item.linkage === "sheepNo") {
      //     this.$set(this.formDataList[index], "typeObj", {
      //       list: params,
      //       listName: ["earLabel", "sheepNo"]
      //     });
      //   }
      // });
      this.listfor({
        formDataList: "formDataList",
        porp: "sheepList",
        list: params,
        listName: ["earLabel", "sheepNo"]
      });
      this.$nextTick(() => {
        this.$set(this.formData, "sheepList", params.map(item => item.sheepNo));
        this.$set(this.formData, "individuationInfoList", params.map(item => {
          return {
            birthday: item.birthday,
            breedTypeNo: item.breedTypeNo,
            breedVarietyNo: item.plantVarietyNo,
            buildingNo: item.buildingNo,
            earLabel: item.earLabel,
            eleEarLabel: item.eleEarLabel,
            farmingTypeNo: item.farmingTypeNo,
            gender: item.gender,
            groupDate: item.groupDate,
            organizationNo: item.organizationNo,
            outlierDate: item.outlierDate,
            sheepNo: item.sheepNo
          }
        }));
      })
      console.log(this.formDataList)
    },
    // 打开羊只筛选弹框
    openSheep(linkage) {
      this.selectType = "more";
      this.sheepSelectDialog = true;
      this.$refs[linkage][0].blur();
    },
    save(formData) {
      // console.log(this.formData);
      // return
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            let formData = { ...this.formData };
            traceConfigApi.edit(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.cancel("formData");
                // this.postId = "";
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.organizationNo = sessionStorage.organizationNo;
            let formData = {
              ...this.formData,
              "traceType": "个体",
              "sourceType": "系统生成"
            }
            traceConfigApi.addBatch(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.cancel("formData");
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep {
  .el-dialog__wrapper {
    .el-dialog {
      min-width: 30%;
    }
  }
}
</style>
